<template>
  <div class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <SearchFrame btnName="添加分类" :hasPermi="['logic:articleCategory:add']" :btnFunc="handleAdd" :model="queryParams"></SearchFrame>
    </transition>
    <el-card shadow="never">
      <el-table v-loading="loading" :data="articleCategoryList">
        <el-table-column label="序号" class-name="num" align="left" width="120">
          <template #default="scope">
            <span>{{scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="分类名称" align="left" prop="categoryName" show-overflow-tooltip />
        <el-table-column label="状态" align="left" prop="isActive">
          <template #default="scope">
            <el-switch v-model="scope.row.status" @change="toggleStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="left" prop="createTime" show-overflow-tooltip />
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['logic:articleCategory:edit']">编辑</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['logic:articleCategory:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改文章分类对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="articleCategoryFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ArticleCategory" lang="ts">
import { listArticleCategory, getArticleCategory, delArticleCategory, addArticleCategory, updateArticleCategory, changeStatus } from '@/api/logic/articleCategory';
import { ArticleCategoryVO, ArticleCategoryQuery, ArticleCategoryForm } from '@/api/logic/articleCategory/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { logic_isactive } = toRefs<any>(proxy?.useDict('logic_isactive'));

const articleCategoryList = ref<ArticleCategoryVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const articleCategoryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ArticleCategoryForm = {
  categoryId: undefined,
  categoryName: undefined,
  sortOrder: undefined,
  isActive: 1
}
const data = reactive<PageData<ArticleCategoryForm, ArticleCategoryQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    categoryName: undefined,
    sortOrder: undefined,
    creator: undefined,
    updater: undefined,
    isActive: undefined,
    params: {
    }
  },
  rules: {
    categoryId: [
      { required: true, message: "产品分类ID不能为空", trigger: "blur" }
    ],
    categoryName: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
    sortOrder: [
      { required: true, message: "排序不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询文章分类列表 */
const getList = async () => {
  loading.value = true;
  const res = await listArticleCategory(queryParams.value);
  res.rows.forEach(el => el.status = !!(el.isActive))
  articleCategoryList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  articleCategoryFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ArticleCategoryVO[]) => {
  ids.value = selection.map(item => item.categoryId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加分类";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ArticleCategoryVO) => {
  reset();
  const _categoryId = row?.categoryId || ids.value[0]
  const res = await getArticleCategory(_categoryId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改文章分类";
}
// 修改状态操作
const toggleStatus = async (row) => {
  try {
    const res = await changeStatus({ categoryId: row.categoryId, isActive: row.isActive ? 0 : 1 })
    proxy?.$modal.msgSuccess(res.msg);
    getList()
  } catch (e) {
    console.log(e)
  }
}

/** 提交按钮 */
const submitForm = () => {
  articleCategoryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.categoryId) {
        await updateArticleCategory(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addArticleCategory(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ArticleCategoryVO) => {
  const _categoryIds = row?.categoryId || ids.value;
  await proxy?.$modal.confirm('确认要删除改该分类吗？').finally(() => loading.value = false);
  await delArticleCategory(_categoryIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/articleCategory/export', {
    ...queryParams.value
  }, `articleCategory_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});

onActivated(() => {
  getList();
})
</script>
